﻿Namespace Framework
    Public Class StickyViewModel
        Inherits DependencyObject
        Implements IStickyComponent

        Public Event DataContextChanged As DependencyPropertyChangedEventHandler

        Public Shared ReadOnly ViewModelProperty As DependencyProperty = DependencyProperty.RegisterAttached("ViewModel", GetType(StickyViewModel), GetType(StickyViewModel), New PropertyMetadata(AddressOf StickyComponentManager.OnStickyComponentChanged))
        Public Shared Function GetViewModel(ByVal d As DependencyObject) As StickyViewModel
            Return d.GetValue(ViewModelProperty)
        End Function
        Public Shared Sub SetViewModel(ByVal d As DependencyObject, ByVal value As StickyViewModel)
            d.SetValue(ViewModelProperty, value)
        End Sub

        Public Shared ReadOnly DataContextProperty As DependencyProperty = FrameworkElement.DataContextProperty.AddOwner(GetType(StickyViewModel))
        Public Property DataContext() As Object
            Get
                Return GetValue(DataContextProperty)
            End Get
            Set(ByVal value As Object)
                SetValue(DataContextProperty, value)
            End Set
        End Property

        Private Sub _DataContextChanged(ByVal sender As Object, ByVal e As DependencyPropertyChangedEventArgs)
            Me.DataContext = e.NewValue
            OnDataContextChanged(sender, e)
        End Sub

        Public ReadOnly Property Mode() As AttachMode Implements IStickyComponent.Mode
            Get
                Return AttachMode.OnLoaded
            End Get
        End Property

        Public Sub OnAttach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnAttach
            Me.DataContext = StickyComponentManager.GetDataContext(sender)
            StickyComponentManager.AttachDataContextChanged(sender, AddressOf _DataContextChanged)
            Attach(sender, e)
        End Sub

        Public Sub OnDetach(ByVal sender As Object, ByVal e As System.EventArgs) Implements IStickyComponent.OnDetach
            Me.DataContext = Nothing
            StickyComponentManager.DetachDataContextChanged(sender, AddressOf _DataContextChanged)
            Detach(sender, e)
        End Sub

        Protected Overridable Sub Attach(ByVal base As DependencyObject, ByVal e As EventArgs)

        End Sub

        Protected Overridable Sub Detach(ByVal base As DependencyObject, ByVal e As EventArgs)

        End Sub

        Protected Overridable Sub OnDataContextChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
            RaiseEvent DataContextChanged(Me, e)
        End Sub
    End Class

End Namespace
